package com.example.mystore.service.impl;

import com.example.mystore.mapper.TrolleyMapper;
import com.example.mystore.mapper.ProductMapper;
import com.example.mystore.model.*;
import com.example.mystore.model.dto.*;
import com.example.mystore.service.TrolleyService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class TrolleyServiceImpl implements TrolleyService {

    @Autowired
    private  TrolleyMapper trolleyMapper;

    @Autowired
    private  ProductMapper productMapper;

    @Autowired
    public TrolleyServiceImpl(TrolleyMapper trolleyMapper) {
        this.trolleyMapper = trolleyMapper;
    }

    @Override
    @Transactional
    public void addTrolley(Trolley trolley) {
        Date now = new Date();
        trolley.setCreated(now);
        trolley.setUpdated(now);
        trolleyMapper.addTrolley(trolley);
    }

    @Override
    public List<TrolleyDto> listById(Integer id) {
        List<TrolleyDto> results = new ArrayList<>();
        List<Trolley> Trolleys = trolleyMapper.listByUserId(id);
        Trolleys.forEach(item -> {
            TrolleyDto TrolleyDto = new TrolleyDto();
            Integer productId = item.getProductId();
            BeanUtils.copyProperties(item, TrolleyDto);
            TrolleyDto.setProductName(productMapper.selectProductById(productId).getName());
            TrolleyDto.setProductPrice(productMapper.selectProductById(productId).getPrice());
            results.add(TrolleyDto);
        });
        return results;
    }

    @Override
    public void changeQuantity(Integer id, Integer quantity) {
        trolleyMapper.changeQuantity(id, quantity);
    }

    @Override
    public void deleteById(Integer id) {
        trolleyMapper.deleteById(id);
    }

    @Override
    public void clearById(Integer id) {
        trolleyMapper.clearById(id);
    }
}
